/*
 * SPDX-FileCopyrightText: 2025 UnionTech Software Technology Co., Ltd.
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

use anyhow::{Ok, Result};

use std::io::Read;

mod cli;
mod commands;
mod encryption;
mod error;
mod utils;
mod zip;
use utzip::error::ZipError;

fn main() -> Result<()> {
    // 解析命令行参数
    let mut args = cli::parse_args();

    // 初始化日志
    {
        let level = log::LevelFilter::Off;

        utils::log::LogConfig::init_logger(
            args.basic_options.quiet,
            args.basic_options.verbose,
            level,
        );
    }

    log::debug!("Parsed arguments: {:#?}", args);

    // 处理从stdin读取文件名的情况
    if args.basic_options.read_names_from_stdin {
        let mut stdin = std::io::stdin();
        let mut buffer = String::new();
        stdin.read_to_string(&mut buffer)?;

        // 分割文件名并添加到文件列表
        for line in buffer.lines() {
            let trimmed = line.trim();
            if !trimmed.is_empty() {
                args.files.push(std::path::PathBuf::from(trimmed));
            }
        }
    }

    // 只出现 -v 或 --version 时，显示版本信息并退出
    if args.basic_options.verbose
        && args.command == cli::Command::Add
        && args.files.is_empty()
        && !args.other.recurse_patterns
        && args.zipfile.is_none()
    {
        cli::show_version();
        return Ok(());
    }

    // 显示许可信息并退出
    if args.other.license {
        cli::show_license();
        return Ok(());
    }

    if args.other.show_command {
        // 获取并显示完整的命令行参数
        let command_line = std::env::args().collect::<Vec<String>>().join(" ");
        println!("Command line:\n{}", command_line);
        return Err(ZipError::Interrupted("show command line".to_string()).into());
    }

    log::info!("Starting rust-zip...");

    // 根据命令行参数执行相应的命令
    match args.command {
        cli::Command::Add => commands::add::execute(&args),
        cli::Command::Delete => commands::delete::execute(&args),
        cli::Command::Update => commands::update::execute(&args),
        cli::Command::Copy => commands::copy::execute(&args),
        cli::Command::Adjust => commands::adjust::execute(&args),
        cli::Command::Test => commands::test::execute(&args),
        cli::Command::List => commands::list::execute(&args),
        // cli::Command::Extract => commands::extract::execute(&args),
        cli::Command::Fix => commands::fix::execute(&args),
    }
}
